package com.example.netty_pipline.pipeline.handler;

import com.example.netty_pipline.pipeline.ChannelHandlerContext;
import com.example.netty_pipline.pipeline.ChannelInboundHandler;
import com.example.netty_pipline.pipeline.ChannelOutboundHandler;

/**
 * 日志处理器 - 记录所有入站和出站事件
 */
public class LoggingHandler implements ChannelInboundHandler, ChannelOutboundHandler {
    
    private final String name;
    
    public LoggingHandler(String name) {
        this.name = name;
    }
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("[" + name + "] Channel active");
        ctx.fireChannelActive();
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("[" + name + "] Channel inactive");
        ctx.fireChannelInactive();
    }
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("[" + name + "] Channel read: " + msg);
        ctx.fireChannelRead(msg);
    }
    
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("[" + name + "] Channel read complete");
        ctx.fireChannelReadComplete();
    }
    
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("[" + name + "] User event triggered: " + evt);
        ctx.fireUserEventTriggered(evt);
    }
    
    @Override
    public void bind(ChannelHandlerContext ctx, Object localAddress) throws Exception {
        System.out.println("[" + name + "] Bind: " + localAddress);
        ctx.bind(localAddress);
    }
    
    @Override
    public void connect(ChannelHandlerContext ctx, Object remoteAddress, Object localAddress) throws Exception {
        System.out.println("[" + name + "] Connect: " + remoteAddress + " -> " + localAddress);
        ctx.connect(remoteAddress, localAddress);
    }
    
    @Override
    public void disconnect(ChannelHandlerContext ctx) throws Exception {
        System.out.println("[" + name + "] Disconnect");
        ctx.disconnect();
    }
    
    @Override
    public void close(ChannelHandlerContext ctx) throws Exception {
        System.out.println("[" + name + "] Close");
        ctx.close();
    }
    
    @Override
    public void write(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("[" + name + "] Write: " + msg);
        ctx.write(msg);
    }
    
    @Override
    public void flush(ChannelHandlerContext ctx) throws Exception {
        System.out.println("[" + name + "] Flush");
        ctx.flush();
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println("[" + name + "] Exception caught: " + cause.getMessage());
        ctx.fireExceptionCaught(cause);
    }
}